package com.itheima.appserver.service;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.appserver.interceptor.UserThreadLocal;
import com.itheima.commons.constants.Constants;
import com.itheima.commons.model.domain.Peach;
import com.itheima.commons.model.domain.UserInfo;
import com.itheima.commons.model.vo.PeachVo;
import com.itheima.dubbo.interfaces.PeachApi;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.Calendar;
import java.util.concurrent.TimeUnit;

@Service
public class PeachblossomService {

    @Reference
    private PeachApi peachApi;

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 获取语音
     *
     * @return
     */
    public PeachVo getPeachblossom() {
        //当天剩余秒
        long secondsLeftToday = 86400 - DateUtils.getFragmentInSeconds(Calendar.getInstance(), Calendar.DATE);
        //当天剩余分
        long minutesLeftToday = secondsLeftToday/60;
        //从redis中获取对应id用户的获取次数，每天六次
        String times = redisTemplate.opsForValue().get(Constants.PEACH_TIMES + UserThreadLocal.getUserId());
        //如果没有获取到，则说明是今天第一次，在redis中存入用户的次数，有效期为一天
        if(StrUtil.isBlank(times)){
            //为空的话

            times = "6";
            redisTemplate.opsForValue().set(Constants.PEACH_TIMES + UserThreadLocal.getUserId(),times,minutesLeftToday, TimeUnit.MINUTES);
        }else {
            times = Convert.toStr(Convert.toInt(times)-1);
            redisTemplate.opsForValue().set(Constants.PEACH_TIMES + UserThreadLocal.getUserId(),times,minutesLeftToday, TimeUnit.MINUTES);

        }

        //随机获取一段音频还有音频的用户信息
        Peach peach = peachApi.queryPeach(UserThreadLocal.getUserId());
        UserInfo userInfo = userInfoService.findUserInfoByUserId(peach.getUserId());
        PeachVo peachVo = PeachVo.makePeachVo(peach, userInfo, Convert.toInt(times));
        return peachVo;
    }

    /**
     * 发送语音(将语音地址保存到库里)
     *
     * @param soundFile
     */
    public void sendPeachblossom(MultipartFile soundFile) {
        userInfoService.savePeach(soundFile);
    }
}
